package com.ysstech.reportworld.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.service.DicvalueService;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.reportworld.entity.TableStandardCheck;
import com.ysstech.reportworld.entity.DemandBugInfo;
import com.ysstech.reportworld.entity.TableStandardCheck;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldStandardCheckTableCodeEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.service.CustomerService;
import com.ysstech.reportworld.service.ModularService;
import com.ysstech.reportworld.service.ReportService;
import com.ysstech.reportworld.service.TableStandardCheckService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报表世界表表校验规则 前端控制器
 * </p>
 *
 * @author lishuangliang
 * @since 2022-04-28
 */
@Controller
@Slf4j
@Api(tags = "报表世界表表校验规则信息管理api")
@RequestMapping("/tableStandardCheck")
public class TableStandardCheckController extends BaseController {
    @Autowired
    private ModularService modularService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private TableStandardCheckService tableStandardCheckService;

    /**
     * 跳转表校验规则信息页面
     *
     * @return
     * @throws Exception
     */
    @YssPermissions(value = {"reportworld:table:standard:check"})
    @ApiOperation(value = "跳转表校验规则信息")
    @YssLog(module = "表校验规则信息管理", remark = "跳转表校验规则信息")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "reportworld/tableStandardCheck";
    }


    @YssPermissions(value = {"reportworld:table:standard:check"})
    @ApiOperation(value = "获取表校验规则信息管理页面初始值")
    @YssLog(module = "表校验规则信息管理", remark = "获取表校验规则信息管理页面初始值")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 状态
        List<Dicvalue> listStatus = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_STATUS.getCode());
        map.put("listStatus", listStatus);
        map.put("listStatus2", listStatus);
        // 标准表校验类型
        List<String> listCheck = ReportWorldStandardCheckTableCodeEnum.getReportWorldStandardCheckTableEnum();
        List<Dicvalue> listCheckTableCode = new ArrayList<>();
        if (!CollectionUtils.isEmpty(listCheck)) {
            for (String code : listCheck) {
                Dicvalue dicvalue = new Dicvalue();
                dicvalue.setValue(code);
                dicvalue.setShowmsg(ReportWorldStandardCheckTableCodeEnum.getEnumDesc(code));
                listCheckTableCode.add(dicvalue);
            }
        }
        map.put("listCheckTableCode", listCheckTableCode);
        map.put("listCheckTableCode2", listCheckTableCode);
        // 所属模块
        List<TreeNode> listModular = modularService.queryModularTree();
        map.put("listModular", listModular);
        // 所属客户
        List<TreeNode> listCustomer = customerService.queryCustomerTree();
        map.put("listCustomer", listCustomer);
        // 所属报表
        List<TreeNode> listReport = reportService.queryReportTree();
        map.put("listReport", listReport);
        // 报表世界所在分层
        List<Dicvalue> listLayered = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_TABLE_LAYERED.getCode());
        map.put("listLayered", listLayered);
        map.put("listLayered2", listLayered);
        return ResultGenerator.getSuccessResult("获取表校验规则信息管理页面初始值成功", map);
    }

    /**
     * 需求BUG列表查询
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:table:standard:check"})
    @ApiOperation(value = "获取所有表校验规则信息")
    @YssLog(module = "表校验规则信息管理", remark = "获取所有表校验规则信息")
    @PostMapping(value = "/listInfo")
    @ResponseBody
    public RestResult listInfo(TableStandardCheck tableStandardCheck, String page, String rows) throws Exception {
        return ResultGenerator.getSuccessResult("获取所有表校验规则信息成功",
                tableStandardCheckService.queryAllTableStandardCheck(tableStandardCheck, this.getPage(page, rows)));
    }

    /**
     * 新增表校验规则信息的方法
     *
     * @param tableStandardCheck
     * @return
     */
    @YssPermissions(value = {"reportworld:table:standard:check:add"})
    @ApiOperation(value = "新增表校验规则信息")
    @YssLog(module = "表校验规则信息管理", remark = "新增表校验规则信息")
    @RequestMapping(value = "/addTableStandardCheck")
    @ResponseBody
    public RestResult addTableStandardCheck(TableStandardCheck tableStandardCheck) throws Exception {
        if (tableStandardCheck == null || StringUtils.isBlank(tableStandardCheck.getCheckCode())
                || StringUtils.isBlank(tableStandardCheck.getCheckValue())) {
            throw new BusinessException("获取表校验规则信息失败，请稍后重试！");
        }
        if (!tableStandardCheck(tableStandardCheck)) {
            throw new BusinessException("已经存在相同的表校验规则信息，请检查！");
        }
        tableStandardCheck.setId(DateUtil.generateUUID());
        tableStandardCheck.setAddTime(LocalDateTime.now());
        tableStandardCheck.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
        tableStandardCheckService.save(tableStandardCheck);
        return ResultGenerator.getSuccessResult("新增表校验规则信息成功！");
    }

    /**
     * 修改表校验规则信息
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:table:standard:check:edit"})
    @ApiOperation(value = "修改表校验规则信息")
    @YssLog(module = "表校验规则信息管理", remark = "修改表校验规则信息")
    @RequestMapping(value = "/editTableStandardCheck")
    @ResponseBody
    public RestResult editTableStandardCheck(TableStandardCheck tableStandardCheck) throws Exception {
        if (tableStandardCheck == null || StringUtils.isBlank(tableStandardCheck.getId())
                || StringUtils.isBlank(tableStandardCheck.getCheckCode())
                || StringUtils.isBlank(tableStandardCheck.getCheckValue())) {
            throw new BusinessException("获取表校验规则信息失败，请稍后重试！");
        }
        if (!tableStandardCheck(tableStandardCheck)) {
            throw new BusinessException("已经存在相同的表校验规则信息，请检查！");
        }
        tableStandardCheck.setEditUser(redisCacheManager.getLoginUserInfo().getLoginId());
        tableStandardCheck.setEditTime(LocalDateTime.now());
        tableStandardCheckService.updateById(tableStandardCheck);
        return ResultGenerator.getSuccessResult("修改表校验规则信息成功！");
    }

    /**
     * 检查是否已经存在
     *
     * @return
     */
    public boolean tableStandardCheck(TableStandardCheck tableStandardCheck) throws Exception {
        if (tableStandardCheck == null || StringUtils.isBlank(tableStandardCheck.getCheckCode())
                || StringUtils.isBlank(tableStandardCheck.getCheckValue())) {
            throw new BusinessException("获取表校验规则信息失败，请稍后重试！");
        }
        QueryWrapper<TableStandardCheck> wrapper = new QueryWrapper();
        wrapper.eq("CHECK_CODE", tableStandardCheck.getCheckCode());
        wrapper.eq("CHECK_VALUE", tableStandardCheck.getCheckValue());
        if (StringUtils.isBlank(tableStandardCheck.getTableNamePrefix())
                && StringUtils.isBlank(tableStandardCheck.getTableNameSuffix())
                && StringUtils.isBlank(tableStandardCheck.getTableNameContain())) {
            throw new BusinessException("没有获取到表前缀，表后缀，表包含的值信息，请稍后重试！");
        }
        if (StringUtils.isNotBlank(tableStandardCheck.getTableNamePrefix())) {
            wrapper.eq("TABLE_NAME_PREFIX", tableStandardCheck.getTableNamePrefix());
        }
        if (StringUtils.isNotBlank(tableStandardCheck.getTableNameSuffix())) {
            wrapper.eq("TABLE_NAME_SUFFIX", tableStandardCheck.getTableNameSuffix());
        }
        if (StringUtils.isNotBlank(tableStandardCheck.getTableNameContain())) {
            wrapper.eq("TABLE_NAME_SUFFIX", tableStandardCheck.getTableNameContain());
        }
        if (StringUtils.isNotBlank(tableStandardCheck.getId())) { // 修改的时候排除自己库里自己这条数据
            wrapper.ne("ID", tableStandardCheck.getId());
        }
        List<TableStandardCheck> checkList = tableStandardCheckService.list(wrapper);
        if (CollectionUtils.isEmpty(checkList)) {
            return true;
        }
        return false;
    }

    /**
     * 删除表校验规则信息
     *
     * @return
     */
    @YssPermissions(value = {"reportworld:table:standard:check:del"})
    @ApiOperation(value = "删除表校验规则信息")
    @YssLog(module = "表校验规则信息管理", remark = "删除表校验规则信息")
    @RequestMapping(value = "/delTableStandardCheck")
    @ResponseBody
    public RestResult delTableStandardCheck(String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取删除用例信息失败，请稍后重试！");
        }
        List<String> tableStandardCheckIds = JSONArray.parseArray(ids, String.class);
        if (!CollectionUtils.isEmpty(tableStandardCheckIds)) {
            tableStandardCheckService.removeByIds(tableStandardCheckIds);
        }
        return ResultGenerator.getSuccessResult("删除表校验规则信息成功！");
    }


}
